package com.kum.handler;

import com.kum.domain.AjaxResult;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @version V1.0
 * @Package com.kum.handler
 * @auhter 枯木Kum
 * @date 2021/4/27-4:29 PM
 * <p>全局统一异常处理类</p>
 */

@RestControllerAdvice
public class BindExceptionHandler {

    @ExceptionHandler(BindException.class)
    public AjaxResult handleBindException(HttpServletRequest request, BindException exception) {
        BindingResult result = exception.getBindingResult();
        final List<FieldError> allErrors = result.getFieldErrors();
        for (FieldError errorMessage : allErrors) {
            return AjaxResult.error(errorMessage.getDefaultMessage());
        }
        return AjaxResult.error("未知错误");
    }


}
